<script setup>
import { ref, computed, onMounted, watch, nextTick } from 'vue'
import { showToast, showConfirmDialog } from 'vant'
import { useRouter, useRoute } from 'vue-router'
import request from '@/utils/request'
import { useLanxinCamera } from '@/composables/useLanxinCamera'

// 获取图片服务器地址配置
const getImageServerUrl = () => {
  // 优先使用localStorage中的配置
  try {
    const savedConfig = localStorage.getItem('APP_CONFIG')
    if (savedConfig) {
      const config = JSON.parse(savedConfig)
      if (config.IMAGE_SERVER_URL) {
        return config.IMAGE_SERVER_URL
      }
    }
  } catch (e) {
    console.warn('解析保存的配置失败:', e)
  }
  
  // 其次使用全局配置
  if (window.APP_CONFIG && window.APP_CONFIG.IMAGE_SERVER_URL) {
    return window.APP_CONFIG.IMAGE_SERVER_URL
  }
  
  // 默认配置
  return 'http://localhost:8070/profile'
}

// 获取用户信息
async function fetchUserInfo() {
  try {
    const response = await request.get('/api/user/userinfo')
    if (response.code === 0) {
      userInfo.value = response
      userRole.value = response.roles || ''
      console.log('用户信息获取成功:', response)
      console.log('用户角色:', response.roles)
      console.log('userRole.value:', userRole.value)
      console.log('isApplicant.value:', isApplicant.value)
      console.log('isWarehouseManager.value:', isWarehouseManager.value)
      console.log('isApprover.value:', isApprover.value)
      
      // 如果是新建模式，更新表单中的申请人和部门信息
      if (mode.value === 'create' && response.data) {
        const userData = response.data
        formData.value.applicant = userData.userName || userData.nickname || userData.loginName || '未知用户'
        formData.value.department = userData.deptName || userData.department || '未知部门'
        console.log('新建模式下已更新用户信息:', {
          applicant: formData.value.applicant,
          department: formData.value.department
        })
      }
    } else {
      console.error('获取用户信息失败:', response)
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

// 判断是否为仓库管理员（兼容多种返回格式/语言）
const isWarehouseManager = computed(() => {
  const role = (userRole.value || '').toString().toLowerCase()
  // 兼容：'仓库管理员' | 'warehouse_manager' | 包含'仓库'或'warehouse'
  return role === '仓库管理员'
    || role === 'warehouse_manager'
    || role.includes('仓库')
    || role.includes('warehouse')
})

// 判断是否为申请人（兼容）
const isApplicant = computed(() => {
  const role = (userRole.value || '').toString().toLowerCase()
  return role === '出库申请人'
    || role === 'applicant'
    || role.includes('申请')
})

// 判断是否为审批人（兼容）
const isApprover = computed(() => {
  const role = (userRole.value || '').toString().toLowerCase()
  return role === '审批人'
    || role === 'approver'
    || role.includes('审批')
})

// 判断是否显示仓库管理员按钮（在“已提交/库存检查”阶段均可处理）
const showWarehouseManagerButtons = computed(() => {
  const allowedStatuses = ['submitted', 'inventory_check']
  const result = isWarehouseManager.value && allowedStatuses.includes(formData.value.status)
  console.log('=== 仓库管理员按钮显示条件检查 ===')
  console.log('isWarehouseManager.value:', isWarehouseManager.value)
  console.log('userRole.value:', userRole.value)
  console.log('formData.value.status:', formData.value.status)
  console.log('showWarehouseManagerButtons:', result)
  console.log('================================')
  return result
})

// 判断是否显示申请人撤回按钮
const showApplicantWithdrawButton = computed(() => {
  return isApplicant.value && formData.value.status === 'submitted'
})

// 判断是否显示申请人重新编辑按钮
const showApplicantReEditButton = computed(() => {
  return isApplicant.value && formData.value.status === 'rejected'
})

// 判断是否显示审批人批准按钮
const showApproverApproveButton = computed(() => {
  return isApprover.value && formData.value.status === 'inventory_sufficient'
})

// 判断是否显示仓库管理员出库完成按钮
const showWarehouseManagerCompleteButton = computed(() => {
  return isWarehouseManager.value && formData.value.status === 'procedures_uploaded'
})

// 构建完整图片URL的辅助函数
function buildImageUrl(filePath) {
  if (!filePath) return ''
  
  // 如果已经是完整URL，直接返回
  if (filePath.startsWith('http://') || filePath.startsWith('https://')) {
    return filePath
  }
  
  // 拼接服务器地址和文件路径
  return `${getImageServerUrl()}${filePath}`
}

const router = useRouter()
const route = useRoute()
const { t } = useI18n()

// 页面模式：'create' | 'edit' | 'view'
const mode = ref('create')
const pageTitle = computed(() => {
  switch (mode.value) {
    case 'create': return '新建申请'
    case 'edit': return '修改申请'
    case 'view': return '申请详情'
    default: return '详情'
  }
})

// 动态设置页面标题
watch(pageTitle, (newTitle) => {
  if (typeof document !== 'undefined') {
    document.title = newTitle
  }
}, { immediate: true })

// 表单数据
const formData = ref({
  id: '',
  title: '',
  description: '',
  images: [],
  applicant: '',
  department: '',
  submitTime: '',
  status: 'draft', // draft, submitted, cancelled
  applicationNo: '',
  createTime: '',
  updateTime: '',
  // 退回原因
  rejectReason: '',
  // 退回时间
  rejectTime: '',
  // 退回人
  rejectorName: ''
})

// 调试函数：检查认证状态
function checkAuthStatus() {
  const token = localStorage.getItem('access_token')
  console.log('=== 认证状态检查 ===')
  console.log('Token存在:', !!token)
  console.log('Token值:', token)
  console.log('Token长度:', token ? token.length : 0)
  console.log('所有localStorage键:', Object.keys(localStorage))
  console.log('==================')
  return token
}

// 测试认证函数
async function testAuth() {
  try {
    console.log('=== 测试认证 ===')
    const token = localStorage.getItem('access_token')
    if (!token) {
      console.log('❌ 没有找到token')
      return false
    }
    
    console.log('✅ Token存在:', token.substring(0, 20) + '...')
    
    // 尝试一个简单的GET请求来测试认证
    // 使用一个更通用的接口来测试
    const response = await request.get('/api/user/userinfo')
    console.log('✅ 认证测试成功:', response)
    return true
  } catch (error) {
    console.log('❌ 认证测试失败:', error.message)
    if (error.response) {
      console.log('响应状态:', error.response.status)
      console.log('响应数据:', error.response.data)
      console.log('响应头:', error.response.headers)
    }
    return false
  }
}

// 图片上传相关
const fileList = ref([])
const maxImages = 3
// 蓝信拍照 - 需求资料
const demandPhotos = ref([])
const { chooseImage: chooseDemandImage, isLanxinAvailable } = useLanxinCamera(demandPhotos)

// 手续文件上传相关
const proceduresFileList = ref([])
const maxProceduresFiles = 5
const proceduresFileInput = ref(null)
// 蓝信拍照 - 手续文件
const proceduresPhotos = ref([])
const { chooseImage: chooseProceduresImage } = useLanxinCamera(proceduresPhotos)

// 图片预览相关
const showImagePreview = ref(false)
const currentImageIndex = ref(0)
const previewImages = ref([])

// 用户信息相关
const userInfo = ref(null)
const userRole = ref('')

// 根据路由参数初始化页面模式和数据
onMounted(() => {
  // 确保页面滚动到顶部
  window.scrollTo(0, 0)
  
  // 检查认证状态
  checkAuthStatus()
  
  // 获取用户信息
  fetchUserInfo()
  
  // 测试认证
  setTimeout(() => {
    testAuth()
  }, 1000)
  
  const id = route.query.id
  const modeParam = route.query.mode || 'create'
  
  mode.value = modeParam
  
  if (id && id !== 'new') {
    loadApplicationData(id)
  } else {
    // 新建模式，初始化空数据
    formData.value = {
      id: '',
      title: '',
      description: '',
      images: [],
      applicant: '', // 将在用户信息获取后设置
      department: '', // 将在用户信息获取后设置
      submitTime: '',
      status: 'draft',
      applicationNo: '',
      createTime: '',
      updateTime: '',
      // 退回原因
      rejectReason: '',
      // 退回时间
      rejectTime: '',
      // 退回人
      rejectorName: ''
    }
  }
})

// 监听路由变化，确保每次进入页面都滚动到顶部
watch(() => route.path, () => {
  // 使用 nextTick 确保 DOM 更新后再滚动
  nextTick(() => {
    window.scrollTo(0, 0)
  })
}, { immediate: true })

// 加载申请数据
async function loadApplicationData(id) {
  try {
    // 显示加载状态
    showToast({
      message: '加载中...',
      duration: 1000
    })
    
    // 调用API获取申请详情
    const response = await request.get(`/api/outbound/detail/${id}`)
    
    if (response.code === 0 && response.application) {
      const data = response.application
      
              // 根据后端返回的数据结构进行适配
        formData.value = {
          id: data.applicationId || data.id,
          title: data.applicationName || '未命名申请',
          description: data.description || '无描述',
          images: data.attachments || [],
          applicant: data.applicantName || '未知申请人',
          department: data.deptName || '未知部门',
          submitTime: data.submitTime || data.createTime || '',
          status: mapStatusFromChinese(data.status),
          applicationNo: data.applicationNo,
          createTime: data.createTime,
          updateTime: data.updateTime,
          // 仓库管理员审批信息
          warehouseManagerId: data.warehouseManagerId1,
          warehouseManagerName: data.warehouseManagerName1,
          inventoryCheckTime: data.inventoryCheckTime,
          inventoryComment: '库存充足，同意申领',
          // 审批人审批信息
          approverId1: data.approverId1,
          approverName1: data.approverName1,
          approverTime1: data.approverTime1,
          approverComment1: data.approverComment1 || '同意出库申请',
          // 线下办理信息
          offlineProcessorId: data.offlineProcessorId,
          offlineProcessorName: data.offlineProcessorName,
          offlineStartTime: data.offlineStartTime,
          // 手续上传信息
          proceduresUploaderId: data.proceduresUploaderId,
          proceduresUploaderName: data.proceduresUploaderName,
          proceduresUploadTime: data.proceduresUploadTime,
          // 退回信息
          rejectReason: data.rejectReason || data.rejectReasonStr || '',
          rejectTime: data.rejectTime || data.rejectTimeStr || '',
          rejectorName: data.rejectorName || data.rejectorNameStr || ''
        }
      
      // 转换图片数据格式，兼容van-uploader
      if (data.attachments && data.attachments.length > 0) {
        // 分离不同类型的附件
        const demandAttachments = data.attachments.filter(att => att.attachmentType === '需求资料')
        const procedureAttachments = data.attachments.filter(att => att.attachmentType === '线下手续')
        
        // 处理需求资料附件（显示在申请资料区域）
        fileList.value = demandAttachments.map((attachment, index) => {
          // 构建完整的图片URL
          const fullImageUrl = buildImageUrl(attachment.filePath) || attachment.url || ''
          
          return {
            url: fullImageUrl,
            file: { uid: attachment.attachmentId || index },
            fileName: attachment.fileName || `image_${index}.jpg`,
            filePath: attachment.filePath || attachment.url,
            isImage: true,
            status: 'done',
            attachmentId: attachment.attachmentId,
            attachmentType: attachment.attachmentType,
            uploadTime: attachment.uploadTime,
            uploadUserName: attachment.uploadUserName
          }
        })
        
        // 处理线下手续附件（显示在手续上传区域）
        proceduresFileList.value = procedureAttachments.map((attachment, index) => {
          // 构建完整的图片URL
          const fullImageUrl = buildImageUrl(attachment.filePath) || attachment.url || ''
          
          return {
            url: fullImageUrl,
            file: { uid: attachment.attachmentId || index },
            fileName: attachment.fileName || `image_${index}.jpg`,
            filePath: attachment.filePath || attachment.url,
            isImage: true,
            status: 'done',
            attachmentId: attachment.attachmentId,
            attachmentType: attachment.attachmentType,
            uploadTime: attachment.uploadTime,
            uploadUserName: attachment.uploadUserName,
            // 标记为已上传的文件，不需要重新上传
            originalFile: null
          }
        })
        
        console.log('需求资料附件数量:', demandAttachments.length)
        console.log('线下手续附件数量:', procedureAttachments.length)
      } else {
        fileList.value = []
        proceduresFileList.value = []
      }
      
      // 根据状态决定页面模式
      // 只有草稿状态（未提交）可以编辑，其他状态都是只读
      if (formData.value.status === 'draft') {
        mode.value = 'edit'
      } else {
        mode.value = 'view'
      }
      
      console.log('申请详情加载成功:', formData.value)
    } else {
      showToast(response.msg || '获取申请详情失败')
      console.error('获取申请详情失败:', response)
    }
  } catch (error) {
    console.error('获取申请详情失败:', error)
    
    // 如果是认证错误，提示用户重新登录
    if (error.response && error.response.status === 401) {
      showToast('登录已过期，请重新登录')
      return
    }
    
    // 如果是网络错误或其他错误
    if (error.message) {
      showToast(`获取详情失败: ${error.message}`)
    } else {
      showToast('获取详情失败，请重试')
    }
  }
}

// 将中文状态映射为英文状态码
function mapStatusFromChinese(chineseStatus) {
  const statusMap = {
    '草稿': 'draft',
    '未提交': 'draft',
    '已提交': 'submitted',
    '库存检查': 'inventory_check',
    '库存不足': 'inventory_insufficient',
    '库存充足': 'inventory_sufficient',
    '线下办理中': 'offline_processing',
    '手续已上传': 'procedures_uploaded',
    '已完成': 'completed',
    '已驳回': 'rejected'
  }
  return statusMap[chineseStatus] || 'draft'
}

// 是否可编辑
const isEditable = computed(() => {
  return mode.value === 'create' || mode.value === 'edit'
})

// 是否显示提交相关信息
const showSubmitInfo = computed(() => {
  return mode.value === 'view' && formData.value.status !== 'draft'
})

// 是否为开发环境
const isDevelopment = computed(() => {
  // 检查是否为开发环境
  return import.meta.env?.MODE === 'development' || 
         window.location.hostname === 'localhost' || 
         window.location.hostname === '127.0.0.1'
})

// 图片上传处理 - 使用van-uploader
function onUploadImage(file) {
  console.log('上传图片:', file)
  console.log('当前fileList长度:', fileList.value.length)
  
  // 检查文件大小（限制为5MB）
  if (file.file.size > 5 * 1024 * 1024) {
    showToast('图片大小不能超过5MB')
    return false
  }
  
  // 检查文件类型
  if (!file.file.type.startsWith('image/')) {
    showToast('请选择图片文件')
    return false
  }
  
  // 检查是否超过最大数量
  if (fileList.value.length >= maxImages) {
    showToast(`最多只能上传${maxImages}张图片`)
    return false
  }
  
  // 添加到文件列表，使用van-uploader期望的数据格式
  const newImage = {
    url: file.content,
    file: { uid: Date.now() },
    fileName: file.file.name,
    filePath: '', // 提交时会上传到服务器
    originalFile: file.file, // 保存原始文件对象，用于后续上传
    isImage: true,
    status: 'done'
  }
  
  console.log('添加新图片:', newImage)
  fileList.value.push(newImage)
  console.log('添加后fileList长度:', fileList.value.length)
  
  showToast('图片选择成功')
  return true
}

// 触发文件选择
function triggerFileSelect() {
  if (fileList.value.length >= maxImages) {
    showToast(`最多只能上传${maxImages}张图片`)
    return
  }
  const remaining = maxImages - fileList.value.length
  if (isLanxinAvailable()) {
    chooseDemandImage({
      maxCount: remaining,
      sourceType: ['camera', 'album'],
      quality: 'low',
      onSuccess: (newPhotos) => {
        newPhotos.forEach((p) => {
          if (fileList.value.length >= maxImages) return
          fileList.value.push({
            url: p.url,
            file: { uid: Date.now() + Math.random() },
            fileName: p.file.name,
            filePath: '',
            originalFile: p.file,
            isImage: true,
            status: 'done'
          })
        })
        showToast('图片选择成功')
      }
    })
    return
  }
  // 回退为原生文件选择
  const fileInput = document.querySelector('input[type="file"]')
  if (fileInput) fileInput.click()
}

// 文件选择处理
function onFileSelected(event) {
  const files = event.target.files
  if (!files || files.length === 0) return
  
  // 检查是否超过最大数量
  if (fileList.value.length + files.length > maxImages) {
    showToast(`最多只能上传${maxImages}张图片`)
    return
  }
  
  // 处理每个选中的文件
  Array.from(files).forEach(file => {
    // 检查文件大小（限制为5MB）
    if (file.size > 5 * 1024 * 1024) {
      showToast(`图片 ${file.name} 大小不能超过5MB`)
      return
    }
    
    // 检查文件类型
    if (!file.type.startsWith('image/')) {
      showToast(`文件 ${file.name} 不是图片格式`)
      return
    }
    
    // 创建预览URL
    const reader = new FileReader()
    reader.onload = (e) => {
      const newImage = {
        url: e.target.result,
        file: { uid: Date.now() + Math.random() },
        fileName: file.name,
        filePath: '', // 提交时会上传到服务器
        originalFile: file // 保存原始文件对象，用于后续上传
      }
      fileList.value.push(newImage)
      showToast(`图片 ${file.name} 选择成功`)
    }
    reader.readAsDataURL(file)
  })
  
  // 清空文件输入，允许重复选择同一文件
  event.target.value = ''
}

// 删除图片
function onDeleteImage(file, detail) {
  console.log('删除图片:', file, detail)
  
  // 从fileList中删除对应的图片
  const index = fileList.value.findIndex(item => 
    item.file.uid === file.file.uid || 
    item.url === file.url ||
    item.fileName === file.fileName
  )
  
  if (index > -1) {
    fileList.value.splice(index, 1)
    showToast('图片删除成功')
  }
  
  return true
}

// 保存草稿
async function saveDraft() {
  if (!formData.value.title.trim()) {
    showToast('请输入申请名称')
    return
  }
  
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    formData.value.status = 'draft'
    showToast('保存成功')
    
    // 如果是新建，跳转到编辑模式
    if (mode.value === 'create') {
      const newId = Date.now().toString()
      formData.value.id = newId
      router.replace({
        path: '/outbound/detail',
        query: { id: newId, mode: 'edit' }
      })
      mode.value = 'edit'
    }
  } catch (error) {
    showToast('保存失败，请重试')
  }
}

// 上传图片到服务器（借鉴uploadProceduresImages方法，一次上传多张图片）
async function uploadImages() {
  try {
    // 创建FormData，只包含文件
    const uploadFormData = new FormData()
    
    // 只上传新选择的文件，跳过已上传的文件
    const newFiles = fileList.value.filter(item => item.originalFile)
    
    if (newFiles.length === 0) {
      console.log('没有新选择的文件需要上传')
      return true
    }
    
    // 添加新选择的文件，参数名使用 'files'
    newFiles.forEach((item, index) => {
      uploadFormData.append('files', item.originalFile)
    })
    
    console.log('开始上传需求资料图片，新文件数量:', newFiles.length)
    
    // 调用后端接口，一次上传多张图片
    const response = await request.post('/api/outbound/upload/files', uploadFormData)
        
        if (response.code === 0) {
      console.log('需求资料图片上传成功:', response)
      
      // 根据后端返回的文件路径更新本地数据
      if (response.filePaths && Array.isArray(response.filePaths)) {
        // 如果后端返回了文件路径数组，按顺序更新
        newFiles.forEach((item, index) => {
          if (response.filePaths[index]) {
            item.filePath = response.filePaths[index]
            console.log(`图片 ${item.fileName} 路径更新为: ${item.filePath}`)
          }
        })
      } else if (response.filePath) {
        // 如果后端只返回了一个路径，为所有文件设置相同的基础路径
        newFiles.forEach((item, index) => {
            item.filePath = response.filePath
          console.log(`图片 ${item.fileName} 路径设置为: ${item.filePath}`)
        })
          } else {
        // 如果后端没有返回路径，生成默认路径
        newFiles.forEach((item, index) => {
          item.filePath = `/upload/${Date.now()}_${index}_${item.fileName}`
          console.warn(`图片 ${item.fileName} 使用默认路径: ${item.filePath}`)
        })
      }
      
      return true
        } else {
          throw new Error(response.msg || '上传失败')
        }
      } catch (error) {
    console.error('需求资料图片上传失败:', error)
        
        // 如果是认证错误，直接返回false，让用户重新登录
        if (error.response && error.response.status === 401) {
          showToast('登录已过期，请重新登录')
          return false
        }
        
        // 如果是网络错误
        if (error.code === 'NETWORK_ERROR' || error.message.includes('Network Error')) {
      showToast('图片上传失败: 网络错误，请检查网络连接')
          return false
        }
        
    showToast(`图片上传失败: ${error.message || '未知错误'}`)
        return false
      }
}

// 提交申请
async function submitApplication() {
  if (!formData.value.title.trim()) {
    showToast('请输入申请名称')
    return
  }
  
  try {
    await showConfirmDialog({
      title: '确认提交',
      message: '提交后将不能修改，确定要提交吗？'
    })
    
    // 先上传图片
    const uploadSuccess = await uploadImages()
    if (!uploadSuccess) {
      return
    }
    
    // 准备提交数据
    const submitData = {
      applicationName: formData.value.title,
      description: formData.value.description || '',
      attachments: fileList.value.map(item => {
        // 确保filePath存在
        if (!item.filePath) {
          console.warn('图片缺少filePath:', item)
          // 如果没有filePath，生成一个默认的
          item.filePath = `/upload/${Date.now()}_${item.fileName}`
        }
        
        return {
          attachmentType: '需求资料',
          fileName: item.fileName,
          filePath: item.filePath
        }
      })
    }
    
    console.log('提交数据:', submitData)
    console.log('图片列表:', fileList.value)
    
    // 调用提交接口
    console.log('开始提交申请，token:', localStorage.getItem('access_token'))
    const response = await request.post('/api/outbound/submit', submitData)
    
    if (response.code === 0) {
      formData.value.status = 'submitted'
      formData.value.submitTime = new Date().toLocaleString('zh-CN')
      formData.value.id = response.applicationId
      formData.value.applicant = response.loginName
      mode.value = 'view'
      
      showToast('提交成功')
    } else {
      showToast(response.msg || '提交失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('提交失败:', error)
      
      // 如果是认证错误，提示用户重新登录
      if (error.response && error.response.status === 401) {
        showToast('登录已过期，请重新登录')
        return
      }
      
      // 如果是网络错误或其他错误
      if (error.message) {
        showToast(`提交失败: ${error.message}`)
      } else {
        showToast('提交失败，请重试')
      }
    }
  }
}

// 删除申请
async function deleteApplication() {
  try {
    await showConfirmDialog({
      title: '确认删除',
      message: '删除后数据将无法恢复，确定要删除吗？'
    })
    
    console.log('开始删除申请，申请ID:', formData.value.id)
    
    // 调用后端删除接口
    const response = await request.delete(`/api/outbound/delete/${formData.value.id}`)
    
    if (response.code === 0) {
      showToast('删除成功')
      // 跳转回列表页
      router.back()
    } else {
      showToast(response.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除申请失败:', error)
      
      // 如果是认证错误，提示用户重新登录
      if (error.response && error.response.status === 401) {
        showToast('登录已过期，请重新登录')
        return
      }
      
      // 如果是网络错误或其他错误
      if (error.message) {
        showToast(`删除失败: ${error.message}`)
      } else {
        showToast('删除失败，请重试')
      }
    }
  }
}

// 撤回申请
async function withdrawApplication() {
  try {
    await showConfirmDialog({
      title: '确认撤回',
      message: '撤回后可以重新编辑申请，确定要撤回吗？'
    })
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    formData.value.status = 'draft'
    formData.value.submitTime = ''
    mode.value = 'edit'
    
    showToast('撤回成功')
  } catch (error) {
    if (error !== 'cancel') {
      showToast('撤回失败，请重试')
    }
  }
}

// 仓库管理员操作 - 库存不足
async function handleInventoryReject() {
  console.log('=== 开始执行库存不足退回操作 ===')
  console.log('当前申请ID:', formData.value.id)
  console.log('当前用户角色:', userRole.value)
  console.log('当前申请状态:', formData.value.status)
  
  try {
    // 弹出退回理由填写框
    const rejectReason = await showRejectReasonDialog()
    
    if (!rejectReason) {
      console.log('用户取消了退回操作')
      return // 用户取消
    }
    
    console.log('用户输入的退回理由:', rejectReason)
    
    // 调用库存不足接口，传递退回理由
    const response = await request.post(`/api/outbound/warehousemanager/reject/${formData.value.id}`, {
      rejectReason: rejectReason
    })
    
    if (response.code === 0) {
      showToast('退回成功')
      // 跳转回列表页
      router.back()
    } else {
      showToast(response.msg || '操作失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('库存不足操作失败:', error)
      showToast('操作失败，请重试')
    }
  }
}

// 显示退回理由填写框
function showRejectReasonDialog() {
  return new Promise((resolve) => {
    // 创建美观的退回理由填写弹窗
    
    // 创建弹窗内容
    const dialogContent = document.createElement('div')
    dialogContent.innerHTML = `
      <div style="padding: 20px;">
        <h3 style="margin: 0 0 15px 0; color: #333; font-size: 18px; text-align: center;">填写退回理由</h3>
        <div style="margin-bottom: 15px;">
          <textarea 
            id="rejectReasonInput" 
            placeholder="请输入退回理由，例如：库存不足、商品缺货等..." 
            style="width: 100%; height: 120px; padding: 12px; border: 1px solid #e8e8e8; border-radius: 8px; resize: vertical; font-family: inherit; font-size: 14px; line-height: 1.5; outline: none;"
          ></textarea>
        </div>
        <div style="text-align: center; color: #999; font-size: 12px; margin-bottom: 20px;">
          请详细说明退回原因，便于申请人了解情况
        </div>
        <div style="display: flex; gap: 12px;">
          <button id="cancelBtn" style="flex: 1; padding: 12px; border: 1px solid #e8e8e8; background: #fff; border-radius: 8px; cursor: pointer; font-size: 14px; color: #666;">取消</button>
          <button id="confirmBtn" style="flex: 1; padding: 12px; border: none; background: #ee0a24; color: white; border-radius: 8px; cursor: pointer; font-size: 14px; font-weight: 500;">确认退回</button>
        </div>
      </div>
    `
    
    // 创建弹窗
    const dialog = document.createElement('div')
    dialog.style.cssText = `
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.6);
      display: flex;
      align-items: center;
      justify-content: center;
      z-index: 9999;
      backdrop-filter: blur(4px);
    `
    
    const dialogBox = document.createElement('div')
    dialogBox.style.cssText = `
      background: white;
      border-radius: 12px;
      box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
      max-width: 420px;
      width: 90%;
      max-height: 90vh;
      overflow: auto;
      animation: dialogSlideIn 0.3s ease-out;
    `
    
    // 添加动画样式
    const style = document.createElement('style')
    style.textContent = `
      @keyframes dialogSlideIn {
        from {
          opacity: 0;
          transform: translateY(-20px) scale(0.95);
        }
        to {
          opacity: 1;
          transform: translateY(0) scale(1);
        }
      }
    `
    document.head.appendChild(style)
    
    dialogBox.appendChild(dialogContent)
    dialog.appendChild(dialogBox)
    document.body.appendChild(dialog)
    
    // 获取输入框和按钮
    const input = dialog.querySelector('#rejectReasonInput')
    const cancelBtn = dialog.querySelector('#cancelBtn')
    const confirmBtn = dialog.querySelector('#confirmBtn')
    
    // 聚焦输入框
    setTimeout(() => input.focus(), 100)
    
    // 绑定事件
    cancelBtn.addEventListener('click', () => {
      document.body.removeChild(dialog)
      document.head.removeChild(style)
      resolve(null) // 返回null表示取消
    })
    
    confirmBtn.addEventListener('click', () => {
      const reason = input.value.trim()
      if (!reason) {
        showToast('请输入退回理由')
        return
      }
      
      if (reason.length < 5) {
        showToast('退回理由至少需要5个字符')
        return
      }
      
      document.body.removeChild(dialog)
      document.head.removeChild(style)
      resolve(reason) // 返回退回理由
    })
    
    // 回车确认
    input.addEventListener('keydown', (e) => {
      if (e.key === 'Enter' && e.ctrlKey) {
        confirmBtn.click()
      }
    })
    
    // 点击背景关闭
    dialog.addEventListener('click', (e) => {
      if (e.target === dialog) {
        document.body.removeChild(dialog)
        document.head.removeChild(style)
        resolve(null)
      }
    })
    
    // ESC键关闭
    const handleEsc = (e) => {
      if (e.key === 'Escape') {
        document.body.removeChild(dialog)
        document.head.removeChild(style)
        document.removeEventListener('keydown', handleEsc)
        resolve(null)
      }
    }
    document.addEventListener('keydown', handleEsc)
  })
}

// 仓库管理员操作 - 确定库存充足
async function handleInventoryApprove() {
  try {
    await showConfirmDialog({
      title: '确认库存充足',
      message: '确定要将此申请标记为库存充足吗？'
    })
    
    // 调用库存充足接口
    const response = await request.post(`/api/outbound/warehousemanager/approve_enough/${formData.value.id}`)
    
    if (response.code === 0) {
      showToast('确认成功')
      // 跳转回列表页
      router.back()
    } else {
      showToast(response.msg || '操作失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('库存充足操作失败:', error)
      showToast('操作失败，请重试')
    }
  }
}

// 审批人操作 - 批准申请
async function handleApproverApprove() {
  try {
    await showConfirmDialog({
      title: '确认批准',
      message: '确定要批准此申请吗？'
    })
    
    // 调用审批通过接口
    const response = await request.post(`/api/outbound/approver/approve/${formData.value.id}`)
    
    if (response.code === 0) {
      showToast('批准成功')
      // 跳转回列表页
      router.back()
    } else {
      showToast(response.msg || '操作失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('审批操作失败:', error)
      showToast('操作失败，请重试')
    }
  }
}

// 仓库管理员操作 - 出库完成
async function handleOutboundComplete() {
  try {
    await showConfirmDialog({
      title: '确认出库完成',
      message: '出库完成后，请登录后台核销库存'
    })
    
    // 调用出库完成接口
    const response = await request.post(`/api/outbound/warehousemanager/complete/${formData.value.id}`)
    
    if (response.code === 0) {
      showToast('出库完成成功')
      // 跳转回列表页
      router.back()
    } else {
      showToast(response.msg || '操作失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('出库完成操作失败:', error)
      showToast('操作失败，请重试')
    }
  }
}

// 申请人重新编辑被退回的申请
function handleReEdit() {
  // 切换到编辑模式
  mode.value = 'edit'
  showToast('已切换到编辑模式，请修改申请内容')
}

// 获取状态显示文本
function getStatusDisplayText(status) {
  const statusTextMap = {
    'draft': '草稿',
    'submitted': '已提交',
    'inventory_check': '库存检查',
    'inventory_insufficient': '库存不足',
    'inventory_sufficient': '库存充足',
    'offline_processing': '线下办理中',
    'procedures_uploaded': '手续已上传',
    'completed': '已完成',
    'rejected': '已驳回'
  }
  return statusTextMap[status] || status
}

// 手续文件上传处理
function onUploadProceduresImage(file) {
  console.log('上传手续文件:', file)
  
  // 检查文件大小（限制为5MB）
  if (file.file.size > 5 * 1024 * 1024) {
    showToast('手续文件大小不能超过5MB')
    return false
  }
  
  // 检查文件类型
  if (!file.file.type.startsWith('image/')) {
    showToast('请选择图片格式的手续文件')
    return false
  }
  
  // 检查是否超过最大数量
  if (proceduresFileList.value.length >= maxProceduresFiles) {
    showToast(`最多只能上传${maxProceduresFiles}张手续文件`)
    return false
  }
  
  // 添加到文件列表
  const newImage = {
    url: file.content,
    file: { uid: Date.now() },
    fileName: file.file.name,
    filePath: '',
    originalFile: file.file,
    isImage: true,
    status: 'done'
  }
  
  proceduresFileList.value.push(newImage)
  showToast('手续文件选择成功')
  return true
}

// 触发手续文件选择
function triggerProceduresFileSelect() {
  if (proceduresFileList.value.length >= maxProceduresFiles) {
    showToast(`最多只能上传${maxProceduresFiles}张手续文件`)
    return
  }
  const remaining = maxProceduresFiles - proceduresFileList.value.length
  if (isLanxinAvailable()) {
    chooseProceduresImage({
      maxCount: remaining,
      sourceType: ['camera', 'album'],
      quality: 'low',
      onSuccess: (newPhotos) => {
        newPhotos.forEach((p) => {
          if (proceduresFileList.value.length >= maxProceduresFiles) return
          proceduresFileList.value.push({
            url: p.url,
            file: { uid: Date.now() + Math.random() },
            fileName: p.file.name,
            filePath: '',
            originalFile: p.file,
            isImage: true,
            status: 'done'
          })
        })
        showToast('手续文件选择成功')
      }
    })
    return
  }
  // 使用ref直接访问DOM元素
  if (proceduresFileInput.value) {
    proceduresFileInput.value.click()
  } else {
    console.error('手续文件输入框未找到')
    showToast('文件选择器初始化失败，请刷新页面重试')
  }
}

// 手续文件选择处理
function onProceduresFileSelected(event) {
  const files = event.target.files
  if (!files || files.length === 0) return
  
  // 检查是否超过最大数量
  if (proceduresFileList.value.length + files.length > maxProceduresFiles) {
    showToast(`最多只能上传${maxProceduresFiles}张手续文件`)
    return
  }
  
  // 处理每个选中的文件
  Array.from(files).forEach(file => {
    // 检查文件大小
    if (file.size > 5 * 1024 * 1024) {
      showToast(`手续文件 ${file.name} 大小不能超过5MB`)
      return
    }
    
    // 检查文件类型
    if (!file.type.startsWith('image/')) {
      showToast(`文件 ${file.name} 不是图片格式`)
      return
    }
    
    // 创建预览URL
    const reader = new FileReader()
    reader.onload = (e) => {
      const newImage = {
        url: e.target.result,
        file: { uid: Date.now() + Math.random() },
        fileName: file.name,
        filePath: '',
        originalFile: file
      }
      proceduresFileList.value.push(newImage)
      showToast(`手续文件 ${file.name} 选择成功`)
    }
    reader.readAsDataURL(file)
  })
  
  // 清空文件输入
  event.target.value = ''
}

// 删除手续文件
function onDeleteProceduresImage(file) {
  console.log('尝试删除手续文件:', file)
  console.log('当前手续文件列表:', proceduresFileList.value)
  
  // 检查是否为已上传的文件
  if (!file.originalFile) {
    showToast('已上传的文件不能删除')
    return false
  }
  
  const index = proceduresFileList.value.findIndex(item => 
    item.file.uid === file.file.uid || 
    item.url === file.url ||
    item.fileName === file.fileName
  )
  
  console.log('找到的索引:', index)
  
  if (index > -1) {
    proceduresFileList.value.splice(index, 1)
    console.log('删除后的文件列表:', proceduresFileList.value)
    showToast('手续文件删除成功')
  } else {
    console.error('未找到要删除的文件')
    showToast('删除失败：未找到文件')
  }
  
  return true
}

// 预览手续文件
function previewProceduresImage(index) {
  if (proceduresFileList.value.length === 0) return
  
  currentImageIndex.value = index
  previewImages.value = proceduresFileList.value.map(item => item.url)
  showImagePreview.value = true
}

// 上传手续文件到服务器（与后端接口匹配）
async function uploadProceduresImages() {
  try {
    // 创建FormData，只包含文件
    const uploadFormData = new FormData()
    
    // 只上传新选择的文件，跳过已上传的文件
    const newFiles = proceduresFileList.value.filter(item => item.originalFile)
    
    if (newFiles.length === 0) {
      console.log('没有新选择的文件需要上传')
      return true
    }
    
    // 添加新选择的文件，参数名必须是 'files'
    newFiles.forEach((item, index) => {
      uploadFormData.append('files', item.originalFile)
    })
    
    console.log('开始上传手续文件，新文件数量:', newFiles.length)
    console.log('申请ID:', formData.value.id)
    
    // 调用后端接口，申请ID通过URL路径传递
    const response = await request.post(`/api/outbound/applicant/upload-procedures/${formData.value.id}`, uploadFormData)
    
    if (response.code === 0) {
      console.log('手续文件上传成功:', response)
      return true
    } else {
      throw new Error(response.msg || '上传失败')
    }
  } catch (error) {
    console.error('手续文件上传失败:', error)
    showToast(`手续文件上传失败: ${error.message || '未知错误'}`)
    return false
  }
}

// 处理上传手续
async function handleUploadProcedures() {
  if (proceduresFileList.value.length === 0) {
    showToast('请先选择要上传的手续文件')
    return
  }
  
  try {
    await showConfirmDialog({
      title: '确认上传',
      message: '确定要上传这些手续文件吗？上传后流程将进入下一步。'
    })
    
    // 直接调用一个接口，后台处理文件上传和流程更新
    const uploadSuccess = await uploadProceduresImages()
    if (!uploadSuccess) {
      return
    }
    
    // 上传成功，显示提示并跳转
    showToast('手续上传成功，流程已进入下一步')
    // 跳转回列表页
    router.back()
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('上传手续失败:', error)
      showToast('上传失败，请重试')
    }
  }
}

// 预览图片
function previewImage(index) {
  if (fileList.value.length === 0) return
  
  currentImageIndex.value = index
  previewImages.value = fileList.value.map(item => item.url)
  showImagePreview.value = true
}

// 关闭图片预览
function closeImagePreview() {
  showImagePreview.value = false
  currentImageIndex.value = 0
}

// 格式化时间
function formatTime(timeStr) {
  if (!timeStr) return ''
  
  try {
    const date = new Date(timeStr)
    const now = new Date()
    const diff = now - date
    
    // 如果是今天，显示时间
    if (diff < 24 * 60 * 60 * 1000) {
      return date.toLocaleTimeString('zh-CN', { 
        hour: '2-digit', 
        minute: '2-digit' 
      })
    }
    
    // 如果是昨天，显示"昨天"
    if (diff < 48 * 60 * 60 * 1000) {
      return '昨天'
    }
    
    // 其他显示日期
    return date.toLocaleDateString('zh-CN', { 
      month: '2-digit', 
      day: '2-digit' 
    })
  } catch (error) {
    return timeStr
  }
}

</script>

<template>
  <div class="detail-page">
    <!-- 主要内容 -->
    <div class="content-wrapper">
      <div class="form-container">
        
        <!-- 申请名称 -->
        <div class="form-item">
          <div class="form-label">
            申请名称
            <span v-if="isEditable" class="required">*</span>
            :
          </div>
          <van-field
            v-if="isEditable"
            v-model="formData.title"
            placeholder="请输入"
            :border="false"
            class="form-input"
          />
          <div v-else class="form-value">{{ formData.title || '未填写' }}</div>
        </div>

        <!-- 申请编号（仅查看模式显示） -->
        <!-- <div v-if="!isEditable && formData.applicationNo" class="form-item">
          <div class="form-label">申请编号:</div>
          <div class="form-value">{{ formData.applicationNo }}</div>
        </div> -->

        <!-- 需求资料图片上传 -->
        <div class="form-item">
          <div class="form-label">
            需求资料(最多{{ maxImages }}张):
          </div>
          
          <!-- 调试信息（开发环境显示） -->
          <!-- <div v-if="isDevelopment && fileList.length > 0" class="debug-info">
            <div class="debug-title">调试信息（图片URL）:</div>
            <div v-for="(item, index) in fileList" :key="index" class="debug-item">
              <span class="debug-label">图片{{ index + 1 }}:</span>
              <span class="debug-url">{{ item.url }}</span>
            </div>
          </div> -->
          
          <div class="upload-section">
            <template v-if="isEditable">
              <!-- 图片预览区域 -->
              <div class="image-preview-area">
                <div 
                  v-for="(item, index) in fileList" 
                  :key="item.file.uid"
                  class="image-preview-item"
                  @click="previewImage(index)"
                >
                  <img :src="item.url" alt="预览图片" class="preview-image" />
                  <div class="delete-btn" @click.stop="onDeleteImage(item)">
                    <van-icon name="cross" />
                  </div>
                </div>
                
                <!-- 上传按钮 -->
                <div 
                  v-if="fileList.length < maxImages"
                  class="upload-btn"
                  @click="triggerFileSelect"
                >
                  <van-icon name="plus" size="24" />
                  <span class="upload-text">选择图片</span>
                </div>
              </div>
              
              <!-- 隐藏的文件输入 -->
              <input
                ref="fileInput"
                type="file"
                accept="image/*"
                multiple
                style="display: none"
                @change="onFileSelected"
              />
            </template>
            <template v-else>
              <div v-if="fileList.length > 0" class="image-list">
                <div 
                  v-for="(item, index) in fileList" 
                  :key="item.file.uid"
                  class="image-item"
                  @click="previewImage(index)"
                >
                  <img :src="item.url" alt="需求资料" />
                </div>
              </div>
              <div v-else class="no-images">暂无图片</div>
            </template>
          </div>
        </div>

        <!-- 描述 -->
        <div class="form-item">
          <div class="form-label">描述:</div>
          <van-field
            v-if="isEditable"
            v-model="formData.description"
            type="textarea"
            placeholder="请输入描述内容"
            rows="4"
            autosize
            :border="false"
            class="form-textarea"
          />
          <div v-else class="form-value">{{ formData.description || '无描述' }}</div>
        </div>

        <!-- 提交信息（仅查看模式显示） -->
        <template v-if="showSubmitInfo">
          <div class="form-item">
            <div class="form-label">申请人:</div>
            <div class="form-value">{{ formData.applicant }}</div>
          </div>
          
          <!-- <div class="form-item">
            <div class="form-label">部门:</div>
            <div class="form-value">{{ formData.department }}</div>
          </div> -->
          
          <!-- <div class="form-item">
            <div class="form-label">申请编号:</div>
            <div class="form-value">{{ formData.applicationNo || '暂无编号' }}</div>
          </div> -->
          
          <div class="form-item">
            <div class="form-label">提交时间:</div>
            <div class="form-value">{{ formData.submitTime }}</div>
          </div>
          
          <!-- <div class="form-item">
            <div class="form-label">创建时间:</div>
            <div class="form-value">{{ formData.createTime }}</div>
          </div> -->
          
          <!-- <div v-if="formData.updateTime" class="form-item">
            <div class="form-label">更新时间:</div>
            <div class="form-value">{{ formData.updateTime }}</div>
          </div> -->
        </template>

        <!-- 仓库管理员审批信息（库存充足状态及之后的状态都显示） -->
        <template v-if="(formData.status === 'inventory_sufficient' || formData.status === 'offline_processing' || formData.status === 'procedures_uploaded' || formData.status === 'completed') && formData.warehouseManagerName">
          <div class="">
            <!-- <h3 class="approval-title">仓库管理员审批信息</h3> -->
            
            <!-- <div class="form-item">
              <div class="form-label">仓库管理员账号:</div>
              <div class="form-value">{{ formData.warehouseManagerId || '未知' }}</div>
            </div> -->
            
            <div class="form-item">
              <div class="form-label">仓库管理员姓名:</div>
              <div class="form-value">{{ formData.warehouseManagerName }}</div>
            </div>
            
            <div class="form-item">
              <div class="form-label">仓库管理员通过时间:</div>
              <div class="form-value">{{ formData.inventoryCheckTime || '未知' }}</div>
            </div>
            
            <div class="form-item">
              <div class="form-label">仓库管理员意见:</div>
              <div class="form-value approval-comment">{{ formData.inventoryComment }}</div>
            </div>
          </div>
        </template>

        <!-- 退回信息（已驳回状态显示，编辑模式下不显示） -->
        <template v-if="formData.status === 'rejected' && formData.rejectReason && mode !== 'edit'">
          <div class="approval-info-section">
            <h3 class="approval-title">退回信息</h3>
            
            <!-- <div class="form-item">
              <div class="form-label">退回人:</div>
              <div class="form-value">{{ formData.rejectorName || '未知' }}</div>
            </div> -->
            
            <!-- <div class="form-item">
              <div class="form-label">退回时间:</div>
              <div class="form-value">{{ formData.rejectTime || '未知' }}</div>
            </div> -->
            
            <div class="form-item">
              <div class="form-label">退回原因:</div>
              <div class="form-value reject-reason">{{ formData.rejectReason }}</div>
            </div>
          </div>
        </template>

        <!-- 审批人审批信息（线下办理中及之后的状态显示） -->
        <template v-if="(formData.status === 'offline_processing' || formData.status === 'procedures_uploaded' || formData.status === 'completed')">
          <div class="">
            <!-- <h3 class="approval-title">审批人审批信息</h3> -->
            
            <!-- <div class="form-item">
              <div class="form-label">审批人账号:</div>
              <div class="form-value">{{ formData.approverId1 || '未知' }}</div>
            </div> -->
            
            <div class="form-item">
              <div class="form-label">审批人姓名:</div>
              <div class="form-value">{{ formData.approverName1 }}</div>
            </div>
            
            <div class="form-item">
              <div class="form-label">审批时间:</div>
              <div class="form-value">{{ formData.approverTime1 || '未知' }}</div>
            </div>
            
            <div class="form-item">
              <div class="form-label">审批意见:</div>
              <div class="form-value approval-comment">{{ formData.approvalComment1 || '同意出库申请' }}</div>
            </div>
          </div>
        </template>

        <!-- 线下办理信息（线下办理中状态显示） -->
        <template v-if="formData.status === 'offline_processing' && formData.offlineProcessorName">
          <div class="approval-info-section">
            <h3 class="approval-title">线下办理信息</h3>
            
            <div class="form-item">
              <div class="form-label">办理人账号:</div>
              <div class="form-value">{{ formData.offlineProcessorId || '未知' }}</div>
            </div>
            
            <div class="form-item">
              <div class="form-label">办理人姓名:</div>
              <div class="form-value">{{ formData.offlineProcessorName }}</div>
            </div>
            
            <div class="form-item">
              <div class="form-label">开始办理时间:</div>
              <div class="form-value">{{ formData.offlineStartTime || '未知' }}</div>
            </div>
            
            <div class="form-item">
              <div class="form-label">办理状态:</div>
              <div class="form-value">线下办理中</div>
            </div>
          </div>
        </template>

        <!-- 手续上传信息（手续已上传状态显示） -->
        <template v-if="formData.status === 'procedures_uploaded' && formData.proceduresUploaderName">
          <div class="approval-info-section">
            <h3 class="approval-title">手续上传信息</h3>
            
            <div class="form-item">
              <div class="form-label">上传人账号:</div>
              <div class="form-value">{{ formData.proceduresUploaderId || '未知' }}</div>
            </div>
            
            <div class="form-item">
              <div class="form-label">上传人姓名:</div>
              <div class="form-value">{{ formData.proceduresUploaderName }}</div>
            </div>
            
            <div class="form-item">
              <div class="form-label">上传时间:</div>
              <div class="form-value">{{ formData.proceduresUploadTime || '未知' }}</div>
            </div>
            
            <div class="form-item">
              <div class="form-label">上传状态:</div>
              <div class="form-value">手续已上传</div>
            </div>
          </div>
        </template>

        <!-- 申请人上传必要手续（线下办理中状态显示） -->
        <template v-if="formData.status === 'offline_processing' && isApplicant">
          <div class="procedures-upload-section">
            <h3 class="approval-title">上传必要手续</h3>
            <div class="upload-description">
              请上传线下办理完成后的必要手续文件，上传完成后流程将进入下一步
            </div>

            <div class="form-label">
              手续上传(最多{{ maxProceduresFiles }}张):
            </div>
            
            <!-- 调试信息 -->
            <!-- <div class="debug-info" style="background: #fff3cd; border: 1px solid #ffeaa7; padding: 8px; margin-bottom: 12px; border-radius: 4px; font-size: 12px;">
              <div>调试信息：</div>
              <div>状态: {{ formData.status }}</div>
              <div>是否申请人: {{ isApplicant }}</div>
              <div>手续文件数量: {{ proceduresFileList.length }}</div>
              <div>最大文件数: {{ maxProceduresFiles }}</div>
            </div> -->
            
            <!-- 手续文件上传区域 -->
            <div class="procedures-upload-area">
              <div class="upload-section">
                <template v-if="proceduresFileList.length > 0">
                  <!-- 已上传的手续文件预览 -->
                  <div class="procedures-preview-area">
                    <div 
                      v-for="(item, index) in proceduresFileList" 
                      :key="item.file.uid"
                      class="procedures-preview-item"
                      @click="previewProceduresImage(index)"
                    >
                      <img :src="item.url" alt="手续文件" class="preview-image" />
                      <!-- 只有新选择的文件才显示删除按钮 -->
                      <div 
                        v-if="item.originalFile" 
                        class="delete-btn" 
                        @click.stop="onDeleteProceduresImage(item)"
                      >
                        <van-icon name="cross" />
                      </div>
                      <!-- 已上传的文件显示上传状态 -->
                      <div v-else class="upload-status-badge">
                        <van-icon name="passed" />
                      </div>
                    </div>
                  </div>
                </template>
                
                <!-- 上传按钮 -->
                <div 
                  v-if="proceduresFileList.length < maxProceduresFiles"
                  class="upload-btn procedures-upload-btn"
                  @click="triggerProceduresFileSelect"
                >
                  <van-icon name="plus" size="24" />
                  <span class="upload-text">选择手续文件</span>
                </div>
              </div>
              
              <!-- 隐藏的文件输入 -->
              <input
                ref="proceduresFileInput"
                type="file"
                accept="image/*"
                multiple
                style="display: none"
                @change="onProceduresFileSelected"
              />
            </div>
            
            <!-- 上传说明 -->
            <!-- <div class="upload-tips">
              <div class="tip-item">
                <van-icon name="info-o" />
                <span>支持图片格式：JPG、PNG、GIF</span>
              </div>
              <div class="tip-item">
                <van-icon name="info-o" />
                <span>单个文件大小不超过5MB</span>
              </div>
              <div class="tip-item">
                <van-icon name="info-o" />
                <span>最多可上传{{ maxProceduresFiles }}张图片</span>
              </div>
            </div> -->
          </div>
        </template>

        <!-- 已上传的手续文件显示（手续已上传状态显示） -->
        <template v-if="(formData.status === 'procedures_uploaded' && proceduresFileList.length > 0) || formData.status === 'completed'">
          <div class="">
            <!-- <h3 class="approval-title">已上传的手续文件</h3>
            <div class="upload-description">
              以下是已上传的手续文件，流程已进入下一步
            </div> -->
            
            <div class="form-label">
              手续文件(共{{ proceduresFileList.length }}张):
            </div>
            
            <!-- 手续文件显示区域 -->
            <div class="procedures-display-area">
              <div class="procedures-preview-area">
                <div 
                  v-for="(item, index) in proceduresFileList" 
                  :key="item.file.uid"
                  class="procedures-preview-item"
                  @click="previewProceduresImage(index)"
                >
                  <img :src="item.url" alt="手续文件" class="preview-image" />
                  <!-- 显示上传状态徽章 -->
                  <div class="upload-status-badge">
                    <van-icon name="passed" />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </template>

        <!-- 审批流程时间线（线下办理中及之后的状态显示）- 暂时隐藏 -->
        <!-- <template v-if="formData.status === 'offline_processing' || formData.status === 'procedures_uploaded' || formData.status === 'completed' || formData.status === 'inventory_sufficient'">
          <div class="approval-timeline-section">
            <h3 class="approval-title">审批流程时间线</h3>
            
            <div class="timeline">
              <div class="timeline-item completed">
                <div class="timeline-icon">
                  <van-icon name="passed" />
                </div>
                <div class="timeline-content">
                  <div class="timeline-title">申请提交</div>
                  <div class="timeline-time">{{ formData.submitTime }}</div>
                  <div class="timeline-user">申请人：{{ formData.applicant }}</div>
                </div>
              </div>
              
              <div class="timeline-item completed" v-if="formData.warehouseManagerName">
                <div class="timeline-icon">
                  <van-icon name="passed" />
                </div>
                <div class="timeline-content">
                  <div class="timeline-title">库存检查通过</div>
                  <div class="timeline-time">{{ formData.inventoryCheckTime }}</div>
                  <div class="timeline-user">审批人：{{ formData.warehouseManagerName }}</div>
                  <div class="timeline-comment">{{ formData.inventoryComment }}</div>
                </div>
              </div>
              
              <div class="timeline-item completed" v-if="formData.approverName">
                <div class="timeline-icon">
                  <van-icon name="passed" />
                </div>
                <div class="timeline-content">
                  <div class="timeline-title">审批通过</div>
                  <div class="timeline-time">{{ formData.approvalTime }}</div>
                  <div class="timeline-user">审批人：{{ formData.approverName }}</div>
                  <div class="timeline-comment">{{ formData.approvalComment }}</div>
                </div>
              </div>
              
              <div class="timeline-item completed" v-if="formData.offlineProcessorName">
                <div class="timeline-icon">
                  <van-icon name="passed" />
                </div>
                <div class="timeline-content">
                  <div class="timeline-title">线下办理</div>
                  <div class="timeline-time">{{ formData.offlineStartTime }}</div>
                  <div class="timeline-user">办理人：{{ formData.offlineProcessorName }}</div>
                </div>
              </div>
              
              <div class="timeline-item completed" v-if="formData.proceduresUploaderName">
                <div class="timeline-icon">
                  <van-icon name="passed" />
                </div>
                <div class="timeline-content">
                  <div class="timeline-title">手续上传</div>
                  <div class="timeline-time">{{ formData.proceduresUploadTime }}</div>
                  <div class="timeline-user">上传人：{{ formData.proceduresUploaderName }}</div>
                </div>
              </div>
              
              <div class="timeline-item current">
                <div class="timeline-icon">
                  <van-icon name="clock-o" />
                </div>
                <div class="timeline-content">
                  <div class="timeline-title">{{ getStatusDisplayText(formData.status) }}</div>
                  <div class="timeline-time">进行中</div>
                </div>
              </div>
            </div>
          </div>
        </template> -->

        <!-- 底部操作按钮 -->
        <div class="action-buttons">
          <!-- 新建/编辑模式按钮 -->
          <template v-if="isEditable">
            <van-button
              v-if="mode === 'edit'"
              type="danger"
              size="large"
              round
              @click="deleteApplication"
              class="action-btn action-delete-btn"
            >
              删除
            </van-button>
            
            <van-button
              type="default"
              size="large"
              round
              @click="saveDraft"
              class="action-btn save-btn"
            >
              保存
            </van-button>
            
            <van-button
              type="primary"
              size="large"
              round
              @click="submitApplication"
              class="action-btn submit-btn"
            >
              提交
            </van-button>
          </template>
          
          <!-- 查看模式按钮 -->
          <template v-else-if="mode === 'view'">
            <!-- 仓库管理员在已提交状态下的特殊按钮 -->
            <template v-if="showWarehouseManagerButtons">
              <van-button
                type="danger"
                size="large"
                round
                @click="handleInventoryReject"
                class="action-btn inventory-insufficient-btn"
              >
                库存不足
              </van-button>
              
              <van-button
                type="success"
                size="large"
                round
                @click="handleInventoryApprove"
                class="action-btn inventory-sufficient-btn"
              >
                确定
              </van-button>
            </template>
            
            <!-- 审批人在库存充足状态下的批准按钮 -->
            <template v-else-if="showApproverApproveButton">
              <van-button
                type="primary"
                size="large"
                round
                @click="handleApproverApprove"
                class="action-btn approve-btn"
              >
                批准
              </van-button>
            </template>
            
            <!-- 申请人在已提交状态下的撤回按钮 -->
            <template v-else-if="showApplicantWithdrawButton">
              <van-button
                type="warning"
                size="large"
                round
                @click="withdrawApplication"
                class="action-btn withdraw-btn"
              >
                撤回申请
              </van-button>
            </template>
            
            <!-- 申请人在被退回状态下的重新编辑按钮 -->
            <template v-else-if="showApplicantReEditButton">
              <van-button
                type="primary"
                size="large"
                round
                @click="handleReEdit"
                class="action-btn re-edit-btn"
              >
                重新编辑
              </van-button>
            </template>
            
            <!-- 申请人在线下办理中状态下的上传手续按钮 -->
            <template v-else-if="formData.status === 'offline_processing' && isApplicant">
              <van-button
                type="success"
                size="large"
                round
                @click="handleUploadProcedures"
                class="action-btn upload-procedures-btn"
              >
                上传手续
              </van-button>
            </template>
            
            <!-- 仓库管理员在手续已上传状态下的出库完成按钮 -->
            <template v-else-if="showWarehouseManagerCompleteButton">
              <van-button
                type="success"
                size="large"
                round
                @click="handleOutboundComplete"
                class="action-btn outbound-complete-btn"
              >
                出库完成
              </van-button>
            </template>
          </template>
        </div>
      </div>
    </div>
    
    <!-- 图片预览组件 -->
    <van-image-preview
      v-model:show="showImagePreview"
      :images="previewImages"
      :start-position="currentImageIndex"
      @close="closeImagePreview"
      :show-index="true"
      :show-indicators="true"
      :closeable="true"
      :close-icon-position="['top-right']"
    />
  </div>
</template>

<style scoped>
.detail-page {
  min-height: 100vh;
  background-color: #f8f9fa;
  padding-bottom: 80px; /* 为底部导航留出空间 */
}

.content-wrapper {
  padding: 0;
}

.form-container {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.form-item {
  margin-bottom: 24px;
}


.form-label {
  color: #2c3e50;
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 12px;
  line-height: 1.4;
}

.required {
  color: #ee0a24;
}

.form-input {
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
  overflow: hidden;
  transition: border-color 0.2s ease;
  padding: 0;
}

.form-input:focus-within {
  border-color: #ff6b6b;
  box-shadow: 0 0 0 2px rgba(255, 107, 107, 0.1);
}

.form-input :deep(.van-field__control) {
  font-size: 16px;
  color: #2c3e50;
  background: transparent;
  padding: 12px 16px;
}

.form-input :deep(.van-field__body) {
  background: transparent;
}

.form-textarea {
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
  overflow: hidden;
  transition: border-color 0.2s ease;
  padding: 0;
}

.form-textarea:focus-within {
  border-color: #ff6b6b;
  box-shadow: 0 0 0 2px rgba(255, 107, 107, 0.1);
}

.form-textarea :deep(.van-field__control) {
  font-size: 16px;
  color: #2c3e50;
  line-height: 1.5;
  background: transparent;
  padding: 12px 16px;
  min-height: 100px;
}

.form-textarea :deep(.van-field__body) {
  background: transparent;
}

.form-value {
  color: #5a6c7d;
  font-size: 16px;
  line-height: 1.5;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.upload-section {
  width: 100%;
}

/* 图片预览区域样式 */
.image-preview-area {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  padding: 12px;
}

.image-preview-item {
  position: relative;
  width: 80px;
  height: 80px;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #e9ecef;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.delete-btn {
  position: absolute;
  top: -8px;
  right: -8px;
  width: 24px;
  height: 24px;
  background: #ee0a24;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 14px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  border: 2px solid white;
  z-index: 10;
}

.upload-btn {
  width: 80px;
  height: 80px;
  border: 2px dashed #d0d7de;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #f8f9fa;
  color: #7c8db5;
  cursor: pointer;
  transition: all 0.2s ease;
}

.upload-btn:hover {
  border-color: #ff6b6b;
  color: #ff6b6b;
  background: #fff5f5;
}

.upload-text {
  font-size: 12px;
  margin-top: 4px;
}

/* 自定义上传组件样式 */
.custom-uploader {
  width: 100%;
}

.custom-uploader :deep(.van-uploader__upload) {
  width: 80px;
  height: 80px;
  border: 2px dashed #d0d7de;
  border-radius: 8px;
  background: #f8f9fa;
  color: #7c8db5;
  transition: all 0.2s ease;
}

.custom-uploader :deep(.van-uploader__upload:hover) {
  border-color: #ff6b6b;
  color: #ff6b6b;
  background: #fff5f5;
}

.custom-uploader :deep(.van-uploader__preview) {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #e9ecef;
}

.custom-uploader :deep(.van-uploader__preview-image) {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.custom-uploader :deep(.van-uploader__delete) {
  top: -8px;
  right: -8px;
  width: 24px;
  height: 24px;
  background: #ee0a24;
  color: white;
  border-radius: 50%;
  font-size: 14px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  border: 2px solid white;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  padding: 12px; /* 增加内边距，为删除按钮预留足够空间 */
}

.image-item {
  position: relative;
  width: 80px;
  height: 80px;
  border-radius: 8px;
  overflow: hidden; /* 改为hidden，让图片信息在底部显示 */
  border: 1px solid #e9ecef;
  cursor: pointer;
  transition: transform 0.2s ease;
}

.image-item:hover {
  transform: scale(1.05);
}

.image-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 7px; /* 给图片本身添加圆角，比容器小1px */
}

.image-info {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 8px;
  border-bottom-left-radius: 7px;
  border-bottom-right-radius: 7px;
  font-size: 12px;
  line-height: 1.3;
}

.file-name {
  font-weight: 600;
  margin-bottom: 2px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.upload-info {
  opacity: 0.8;
  font-size: 11px;
}

/* 调试信息样式 */
.debug-info {
  background: #f0f8ff;
  border: 1px solid #b0d4f1;
  border-radius: 6px;
  padding: 12px;
  margin-bottom: 12px;
  font-family: 'Courier New', monospace;
}

.debug-title {
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 8px;
  font-size: 14px;
}

.debug-item {
  margin-bottom: 6px;
  font-size: 12px;
}

.debug-label {
  color: #7f8c8d;
  margin-right: 8px;
  font-weight: 500;
}

.debug-url {
  color: #e74c3c;
  word-break: break-all;
  background: #fff;
  padding: 2px 6px;
  border-radius: 3px;
  border: 1px solid #ddd;
}

.delete-icon {
  position: absolute;
  top: -8px;
  right: -8px;
  width: 24px;
  height: 24px;
  background: #ee0a24;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  cursor: pointer;
  z-index: 10;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  border: 2px solid white;
}

.upload-btn {
  width: 80px;
  height: 80px;
  border: 2px dashed #d0d7de;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f8f9fa;
  color: #7c8db5;
  cursor: pointer;
  transition: all 0.2s ease;
}

.upload-btn:hover {
  border-color: #ff6b6b;
  color: #ff6b6b;
  background: #fff5f5;
}

.no-images {
  color: #7c8db5;
  font-size: 14px;
  text-align: center;
  padding: 40px 0;
}

.action-buttons {
  padding: 20px;
  margin-top: 16px;
  border-radius: 12px;
  display: flex;
  gap: 12px;
}

.action-btn {
  flex: 1;
  height: 48px;
  font-size: 16px;
  font-weight: 600;
}

.action-delete-btn {
  background: #ee0a24;
  border: none;
}

.save-btn {
  background: #f8f9fa;
  color: #2c3e50;
  border: 1px solid #e9ecef;
}

.submit-btn {
  background: linear-gradient(135deg, #ff6b6b 0%, #feca57 100%);
  border: none;
}

.withdraw-btn {
  background: #ff976a;
  border: none;
}

.inventory-insufficient-btn {
  background: #ee0a24;
  border: none;
}

.inventory-sufficient-btn {
  background: #07c160;
  border: none;
}

.approve-btn {
  background: #1989fa;
  border: none;
}

.re-edit-btn {
  background: #1989fa;
  border: none;
}

/* 审批信息区域样式 */
.approval-info-section {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  padding: 16px;
  margin-top: 20px;
}

.approval-title {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  text-align: center;
  padding-bottom: 12px;
  border-bottom: 2px solid #1989fa;
}

.approval-comment {
  background: #e3f2fd;
  border: 1px solid #bbdefb;
  color: #1565c0;
  font-weight: 500;
}

.reject-reason {
  background: #ffebee;
  border: 1px solid #ffcdd2;
  color: #c62828;
  font-weight: 500;
  padding: 12px;
  border-radius: 6px;
  line-height: 1.5;
}

/* 审批流程时间线样式 */
.approval-timeline-section {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  padding: 16px;
  margin-top: 20px;
}

.timeline {
  position: relative;
  padding-left: 20px;
}

.timeline::before {
  content: '';
  position: absolute;
  left: 15px;
  top: 0;
  bottom: 0;
  width: 2px;
  background: #e9ecef;
}

.timeline-item {
  position: relative;
  margin-bottom: 24px;
  display: flex;
  align-items: flex-start;
}

.timeline-item:last-child {
  margin-bottom: 0;
}

.timeline-icon {
  position: absolute;
  left: -20px;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 16px;
  z-index: 2;
}

.timeline-item.completed .timeline-icon {
  background: #07c160;
}

.timeline-item.current .timeline-icon {
  background: #1989fa;
}

.timeline-content {
  flex: 1;
  margin-left: 16px;
}

.timeline-title {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 8px;
}

.timeline-time {
  font-size: 14px;
  color: #7c8db5;
  margin-bottom: 4px;
}

.timeline-user {
  font-size: 14px;
  color: #5a6c7d;
  margin-bottom: 4px;
}

.timeline-comment {
  font-size: 13px;
  color: #1989fa;
  background: #e3f2fd;
  padding: 6px 8px;
  border-radius: 4px;
  border: 1px solid #bbdefb;
  display: inline-block;
}

/* 手续上传区域样式 */
.procedures-upload-section {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  padding: 16px;
  margin-top: 20px;
}

.upload-description {
  color: #5a6c7d;
  font-size: 14px;
  line-height: 1.5;
  margin-bottom: 16px;
  text-align: center;
  padding: 12px;
  background: #e3f2fd;
  border-radius: 6px;
  border: 1px solid #bbdefb;
}

.procedures-upload-area {
  margin-bottom: 16px;
}

.procedures-preview-area {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 12px;
}

.procedures-preview-item {
  position: relative;
  width: 80px;
  height: 80px;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #e9ecef;
}

.procedures-upload-btn {
  width: 80px;
  height: 80px;
  border: 2px dashed #1989fa;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #f0f8ff;
  color: #1989fa;
  cursor: pointer;
  transition: all 0.2s ease;
}

.procedures-upload-btn:hover {
  border-color: #1565c0;
  color: #1565c0;
  background: #e3f2fd;
}

.upload-tips {
  background: #fff3cd;
  border: 1px solid #ffeaa7;
  border-radius: 6px;
  padding: 12px;
}

.tip-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 6px;
  font-size: 12px;
  color: #856404;
}

.tip-item:last-child {
  margin-bottom: 0;
}

.tip-item .van-icon {
  color: #f39c12;
  font-size: 14px;
}

.upload-procedures-btn {
  background: #07c160;
  border: none;
}

.outbound-complete-btn {
  background: #07c160;
  border: none;
}

.upload-status-badge {
  position: absolute;
  top: -8px;
  right: -8px;
  width: 24px;
  height: 24px;
  background: #07c160;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  border: 2px solid white;
  z-index: 10;
}

/* 已上传手续文件显示区域样式 */
.procedures-display-section {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  padding: 16px;
  margin-top: 20px;
}

.procedures-display-area {
  margin-bottom: 16px;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .content-wrapper {
    padding: 2px;
  }
  
  .form-container {
    padding: 16px;
  }
  
  .action-buttons {
    /* 贴底、允许按钮自然换行为两列网格，不使用横向滚动 */
    position: sticky;
    bottom: 0;
    background: #ffffff;
    flex-wrap: wrap;
    gap: 8px;
    padding-bottom: calc(12px + env(safe-area-inset-bottom));
  }
  
  .action-btn {
    /* 两列等分排布，移动端不横向滚动 */
    flex: 1 1 calc(50% - 4px);
    min-width: auto;
    height: 44px;
    font-size: 15px;
  }
  
  /* 表单字段允许自然换行显示完整内容 */
  .form-label,
  .form-value,
  .form-textarea :deep(.van-field__control),
  .form-input :deep(.van-field__control) {
    white-space: normal;
    overflow: visible;
    text-overflow: clip;
  }
}

/* 暗色模式支持 */
@media (prefers-color-scheme: dark) {
  .detail-page {
    background-color: #1a1a1a;
  }
  
  .form-container {
    background: #2c2c2c;
    border-color: #404040;
  }
  
  .form-label {
    color: #e0e0e0;
  }
  
  .form-value {
    background: #404040;
    border-color: #606060;
    color: #c0c0c0;
  }
  
  .action-buttons {
    background: #2c2c2c;
    border-color: #404040;
  }
  
  .save-btn {
    background: #404040;
    color: #e0e0e0;
    border-color: #606060;
  }
}
</style>

<route lang="json5">
{
  name: 'OutboundDetail',
  meta: {
    title: '申请详情'
  }
}
</route> 